package com.koron.log.util;

import com.alibaba.fastjson.JSON;
import com.koron.common.core.business.log.entity.po.LogOperatePo;
import com.koron.log.service.LogOperateService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

/**
 * @ClassName KrSubcribe
 * @description 订阅程序
 * @Author zhouj
 * @Date 2021/10/20 16:18
 */
@Slf4j
@Component
public class OperateLogSubcribe implements MessageListener {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private LogOperateService logOperateService;

    @Override
    public void onMessage(Message message, byte[] pattern) {
        log.info("接收数据:{}", message.toString());
        log.info("订阅频道:{}", new String(message.getChannel()));

        cacheMessage(message);
    }

    public void cacheMessage(Message message) {

        String messageStr = message.toString();
        if (StringUtils.isNotEmpty(messageStr)) {
            logOperateService.insert(JSON.parseObject(message.toString(), LogOperatePo.class));
        }
    }
}
